<?php

namespace common\jobs;

use Yii;
use yii\base\Exception;
use common\helpers\ArrayHelper;
use common\models\shop\ShopOrderRefund;
use common\models\shop\ShopOrderServiceApply;
use common\models\shop\ShopServiceSupportWorkflow;

/**
 * 任务流自动过期处理
 * Class ServiceWorkflowJob.
 */
class ContractServiceWorkflowJob extends \yii\base\BaseObject implements \yii\queue\RetryableJobInterface {

    public $modelClass = null;
    public $model_id = null;
    public $workflowClass = null;
    public $workflow_id = null;
    public $options = [];

    /**
     * @param \yii\queue\Queue $queue
     * @return mixed|void
     * @throws Exception
     */
    public function execute($queue) {
        if (empty($this->options)) {
            Yii::error([
                'status' => '流程中断',
                'error' => 'need options!',
            ], __METHOD__);
            throw new Exception('need options!');
        }
        $model = $this->getModel();
        $workflow = $this->getWorkflow();
        if (!$model->validateContinueWorkflow($workflow)) {
            Yii::error([
                'status' => '流程中断',
                'error' => $model->getErrors(),
            ], __METHOD__);
            return true;
        }
        $status = $workflow->updateWorkflowInstance($model, $workflow);
        if (!$status) {
            Yii::error([
                'status' => '流程中断',
                'error' => '[AUTOWORK FAIL:' . $this->model_id . ']' . $workflow->getErrorMsg(),
            ], __METHOD__);
            throw new Exception('[AUTOWORK FAIL:' . $this->model_id . ']' . $workflow->getErrorMsg());
        }
    }

    /**
     * @return ShopOrderRefund|ShopOrderServiceApply
     * @throws Exception
     */
    public function getModel() {
        $modelClass = ArrayHelper::getValue($this->options, 'modelClass');
        $pk = ArrayHelper::getValue($this->options, 'model_id');
        if ($modelClass == null || $pk == null) {
            throw new Exception('need model!');
        }
        return $modelClass::findOrFail($pk);
    }

    /**
     * @return ShopServiceSupportWorkflow
     * @throws Exception
     */
    public function getWorkflow() {
        $modelClass = ArrayHelper::getValue($this->options, 'workflowClass');
        $pk = ArrayHelper::getValue($this->options, 'workflow_id');
        if ($modelClass == null || $pk == null) {
            Yii::error([
                'status' => '流程中断',
                'error' => 'need workflow!',
            ], __METHOD__);
            throw new Exception('need workflow!');
        }
        return $modelClass::findOrFail($pk);
    }

    /**
     * @inheritdoc
     */
    public function getTtr() {
        return 60;
    }

    /**
     * @inheritdoc
     */
    public function canRetry($attempt, $error) {
        Yii::error($error, __METHOD__);
        return $attempt < 3;
    }

}
